//
//  LCRefeshControl.swift
//  SinaWeiBo
//
//  Created by mac on 16/12/11.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
let refeshHeight:CGFloat = 50
//定义一个枚举来标示下拉刷新的三种状态

enum LCRefeshControlType{
    case normol
    case pullind
    case refeshing
}


//自定义下拉刷新
class LCRefeshControl: UIControl {
    //设置一个变量来记录下拉刷新的状态
    private var refeshType:LCRefeshControlType = .normol{
        didSet{
            switch refeshType {
            case .normol:
                print("下拉刷新")
                activityView.stopAnimating()
                iconImage.isHidden = false
                messageLabel.text = "下拉刷新"
                UIView.animate(withDuration: 0.3, animations: { 
                    self.iconImage.transform = CGAffineTransform.identity
                })
                
                if oldValue == .refeshing {
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.currentScrollView?.contentInset.top -= refeshHeight
                    })
                }
      
                
            case .pullind:
                print("松手刷新")
                messageLabel.text = "松手刷新"
                //翻转箭头
                UIView.animate(withDuration: 0.3, animations: { 
                      self.iconImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
            case .refeshing:
                print("正在刷新")
                activityView.startAnimating()
                iconImage.isHidden = true
                messageLabel.text = "正在刷新.."
                
                //设置刷新控件停留位置
                UIView.animate(withDuration: 0.25, animations: { 
                    self.currentScrollView?.contentInset.top += refeshHeight
                })
                //加载数据
                sendActions(for: .valueChanged)
            }
            
            
        }
        
        
        
    }
    
    //定义变量用来记录父控件
    private var currentScrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    
        setupUI()
    }
    //MARK: 懒加载控件
    //箭头控件
    private lazy var iconImage:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //菊花控件
    private lazy var activityView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    //内容label
    private lazy var messageLabel:UILabel = {
        let label = UILabel()
        label.textColor = UIColor.gray
        label.font = UIFont.systemFont(ofSize: 12)
        label.text = "下拉刷新"
        return label
    }()

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        self.backgroundColor = UIColor.red
        //添加子控件
        addSubview(iconImage)
        addSubview(activityView)
        addSubview(messageLabel)
        
        
        //设置约束
        iconImage.translatesAutoresizingMaskIntoConstraints = false
        activityView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImage, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImage, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: activityView, attribute: .centerY, relatedBy: .equal, toItem: iconImage, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: activityView, attribute: .centerX, relatedBy: .equal, toItem: iconImage, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        
        
    }
    //1获取父控件
    override func willMove(toSuperview newSuperview: UIView?) {
        //判断父控件是否能滚动
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        //设置下拉刷新view的大小
        self.size =  CGSize(width: scrollView.frame.size.width, height: refeshHeight)
        self.frame.origin.y -= refeshHeight
        
        currentScrollView = scrollView
        //设置KV0监控父控件的偏移量
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
        
    }
    //2监控偏移量
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //1获取偏移量
        let contentOffsetY:CGFloat = currentScrollView!.contentOffset.y
        //2找到临界点
        let criticalPoint:CGFloat = -(currentScrollView!.contentInset.top + refeshHeight)
        
        //3根据偏移量来设置下拉刷新的状态
        if currentScrollView!.isDragging {
            //如果是在拖拽的状态
            if contentOffsetY < criticalPoint && refeshType == .normol {
    
                refeshType = .pullind
            }
            
            if contentOffsetY >= criticalPoint && refeshType == .pullind{
                
                refeshType = .normol
            }
        }else{
            //松手的情况
            if  refeshType == .pullind {
                refeshType = .refeshing
            }
            
        }
        
        
    }
    
    func endRefesh(){
        refeshType = .normol
    }

    //4根据状态做相应的操作
    //5移除KVO
    deinit {
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

}
